package cn.jbooter.ctx.autoconfigure.startup;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.OrderComparator;

import cn.jbooter.ctx.autoconfigure.startup.intf.ApplicationStartupInitializer;

/**
 * spring上下文context初始化完毕后监听器
 *
 * ApplicationRunner和@Order注解配合,也可以实现同样的功能:在容器启动成功后执行.
 *
 * @author HeJian
 *
 */
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent>{
	private final Logger logger = LoggerFactory.getLogger(ApplicationContextListener.class);
	
	
	@Autowired(required=false)
	private List<ApplicationStartupInitializer> initializerList;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		ApplicationContext ctx = event.getApplicationContext();
		if(ctx.getParent() == null){
			if(initializerList!=null && initializerList.size()>0) {
				logger.info(">>>>>> Initializing custome component ......");
				OrderComparator.sort(initializerList);
				for(ApplicationStartupInitializer initializer: initializerList) {
					initializer.initialize(ctx);
				}
			}
		}
	}


}
